package com.baishui.gateway.handler;

import com.baishui.gateway.constant.HttpConstants;
import com.baishui.gateway.context.GateWayRouteContext;
import com.baishui.gateway.context.GateWayRouteContextHelper;
import com.baishui.gateway.response.ResponseProcesser;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.http.Cookie;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.RoutingContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.function.BiConsumer;

@Component
public class InitializeHandler implements Handler<RoutingContext> {
    private final static Logger log = LoggerFactory.getLogger(InitializeHandler.class);

    @Autowired
    private ResponseProcesser responseProcesser;

    @Override
    public void handle(RoutingContext context) {
        HttpServerRequest request = context.request();
        String path = request.path();
        log.info("request path is {}", path);

        try {
            doBase(context);
            context.next();
        } catch (Throwable throwable) {
            log.error("something error!", throwable);
            responseProcesser.writeError(context, GateWayRouteContextHelper.getContext(context));
        } finally {

        }
    }

    private void doBase(RoutingContext routingContext) {
        GateWayRouteContext context = new GateWayRouteContext();
        HttpServerRequest request = routingContext.request();
        routingContext.getAcceptableContentType();
        doParam.accept(request, context);
        doCookie.accept(request, context);
        doContentType.accept(request, context);
        doBody.accept(request, context);
        GateWayRouteContextHelper.setContext(routingContext, context);
    }

    private BiConsumer<HttpServerRequest, GateWayRouteContext> doParam = (r, c) -> {
        // parameters
        MultiMap params = r.params();
        MultiMap formAttributes = r.formAttributes();
        c.setPath(r.path());
    };

    private BiConsumer<HttpServerRequest, GateWayRouteContext> doCookie = (r, c) -> {
        Map<String, Cookie> cookieMap = r.cookieMap();
        c.setCookies(cookieMap);
    };

    private BiConsumer<HttpServerRequest, GateWayRouteContext> doContentType = (r, c) -> {
        String header = r.getHeader(HttpConstants.CONTENT_TYPE);
        System.out.println(header);
    };

    private BiConsumer<HttpServerRequest, GateWayRouteContext> doBody = (r, c) -> {
    };

}
